package com.ksyun.campus.metaserver.services;

import com.alibaba.fastjson.JSONObject;
import com.ksyun.campus.metaserver.config.metaserverconfig.MetaServerConfigProperties;
import com.ksyun.campus.metaserver.domain.MetaServerInfo;
import com.ksyun.campus.metaserver.domain.StatInfo;
import com.ksyun.campus.metaserver.util.MyZkSerializer;
import lombok.extern.slf4j.Slf4j;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class HeartBeatService {
    @Resource
    MetaServerConfigProperties metaServerConfigProperties;
    @Resource
    private ZkClient zkClient;
    @Resource
    private MetaServerInfo metaServerInfo;

    @Resource
    private Map<String, StatInfo> StatInfoMap;


    @Scheduled(cron = "0/3 * * * * ?")
    public void heartBeat() {
        // 同步metaServer信息到zookeeper节点 记录信息

        // 解决zk写入数据乱码
        zkClient.setZkSerializer(new MyZkSerializer());
        zkClient.writeData(metaServerConfigProperties.getFullNode(), JSONObject.toJSONString(metaServerInfo));
        File file = new File(metaServerInfo.getFileName());

        if (!file.exists()) {
            try {
                file.createNewFile();
                log.info("metaServer recovery文件为：{}", metaServerInfo.getFileName());
            } catch (IOException e) {
                log.debug("创建recovery文件失败！");
            }
        }
        // todo 更新元数据，为json格式


        // 同步到从节点metaserver
        List<String> metaserverNodes = zkClient.getChildren(metaServerConfigProperties.getRootName());
        MetaServerInfo slaveMetaServer = null;
        for (String node : metaserverNodes) {
            if (!node.equals(metaServerConfigProperties.getFullNode())) {
                slaveMetaServer = JSONObject.parseObject(zkClient.readData(node), MetaServerInfo.class);
                // todo 更新元数据
            }
        }

    }


}
